//    PollIT - Tool to make decisions of anything
//    Copyright (C) 2011 Jukka Hell
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import fi.hell.pollit.util.CookieService;
import fi.hell.pollit.domain.User;
/**
 *
 * @author jukka
 */
class AuthenticateFilters {
	CookieService cookieService;

    // Restricted controller:action map
    // Wild card (*) supported which means that all actions needs permissions
    // Negation (!) supported which means that all but this action needs permissions
    Map<String, String> restrictedActions = [
        "poll":"*",
        "opt":"*",
        "user":["!login"],
        "vote":["!save"]
    ];

    public filters = {
        // Do filter for all url:s
        all(controller:'*', action:'*') {
            before = {
                User loggedInUser = User.getLoggedInUser();

                if (needsPermission(controllerName, actionName) && !hasPermission(loggedInUser)) {
                    redirect(url:grailsApplication.config.grails.serverURL);
                    return false;
                }
            }
        }
    }

    /**
     * Simple check to see if user has permission for requested url
     * If user is logged in, permission is granted
     */
    boolean hasPermission(User u) {
        return (u) ? true : false;
    }

    /**
     * Check if requested controller and/or action needs permissions
     */
    boolean needsPermission(String controller, String action) {
        if (!controller && !action) {
            return false;
        }

        // If all actions in current controller are restricted
        if (restrictedActions[controller] == "*") {
            return true;
        }

        // If action is found from action list or not found from allowed list
        if (restrictedActions[controller]?.contains(action) || (restrictedActions[controller] && !restrictedActions[controller]?.contains("!"+action))) {
            return true;
        }

        return false;
    }
}

